package com.example.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class ShopAuthFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.err.println("全局路由器执行了");

        ServerHttpRequest request = exchange.getRequest();      // 请求对象
        System.out.println("请求URL: " + request.getURI());
        System.out.println("请求参数: " + request.getQueryParams());
        
        ServerHttpResponse response = exchange.getResponse();   // 应答对象
        String token = request.getQueryParams().getFirst("token");
        System.out.println("Token参数值: " + token);
        
        if (StringUtils.isBlank(token)){  // 如果传递的token是null,"",或者空白符
            System.err.println("Token为空，拒绝访问");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }else{
            // 验证token的有效性
            // 如果token不合法，返回401
            System.out.println("Token验证通过");
        }
        return chain.filter(exchange);        //  放行
    }
}
